<?php
namespace app\mxty\model;

use think\Model;
use think\model\concern\SoftDelete;

class Arena extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_arena';
    protected $pk = 'arena_id';

    public function parts()
    {
        return $this->hasMany(ArenaPart::class);
    }

    public function timeTemplate()
    {
        return $this->belongsTo(TimeTemplate::class);
    }

    public function sessions()
    {
        return $this->hasManyThrough(
            ArenaPartTimeFragment::class,
            ArenaPart::class
        );
    }

    // 获取指定 id 的场地下所有半场的空闲场次信息
    public function getIdleAreanInfoById($date, $arenaId)
    {
        // 查询指定id且状态为0（空闲）的场地，及其下所有半场
        $arena = self::with([
            'parts' => function ($query) use ($date) {
                // 限定半场的状态为0（空闲），查询该半场下所有场次信息，及对应场次的预订记录
                $query
                    ->with([
                        'sessions' => [
                            'bookings' => function ($query) use ($date) {
                                // 限定场次预订记录为指定日期内，预订记录暂以 update_time 排序
                                $query
                                    ->whereTime('start_date', '<=', $date)
                                    ->whereTime('end_date', '>=', $date)
                                    ->order('update_time desc');
                            },
                            'fragment'
                        ],
                    ])
                    ->where('status', 0);
            }
        ])
            ->where('status', 0)
            ->find($arenaId);

        return $arena;
    }

    // 获取所有空闲状态的场地
    public function getAllIdleAreans($date)
    {
        // 查找所有空闲的场地
        $list = self::with([
            // 查找每个场地下所有空闲的半场
            'parts' => function ($query) use ($date) {
                $query
                    ->with([
                        'sessions' => [
                            'bookings' => function ($query) use ($date) {
                                $query
                                    ->whereTime('start_date', '<=', $date)
                                    ->whereTime('end_date', '>=', $date)
                                    ->order('update_time desc');
                            },
                        ],
                    ])
                    ->where('status', 0);
            },
        ])
            ->where('status', 0)
            ->select();

        return $list;
    }
}
